package com.stonedt.spider.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.stonedt.spider.entity.ApiCall;
import com.stonedt.spider.util.ApiCallUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: 康涵博
 * @ClassName: ApiCallController
 * @Time: 2024/4/30 13:48
 * @Description:
 */
@RestController
@RequestMapping
public class ApiCallController {
    /**
     * @Author 康涵博
     * @Description 通过返回的html代码拼装关键词后调用api回答问题并返回
     * @Date 15:31 2024/4/30
     * @Param [com.alibaba.fastjson.JSONObject]
     * @return com.alibaba.fastjson.JSONObject
     */

    @PostMapping("/apiCall")
    public JSONObject apiCall( @RequestBody ApiCall apiCall){
        System.out.println("入参对象：" + apiCall);
        //先把html里双引号改为单引号
//        String html = apiCall.getPrompt().replace("\"", "'");
        Document doc = Jsoup.parse(apiCall.getPrompt());
        //返回的html的text格式
        String text = doc.select("body").text();

        StringBuilder builder = new StringBuilder();
        builder.append(text);
        if(apiCall.getCallWord() == null){
            builder.append("#抽取内容中的列表的标题、时间、摘要，返回结果只需要第一条，一共只需要1条返回结果，用json格式输出。");
        }else {
            builder.append(apiCall.getCallWord());
        }
        String string = builder.toString();

        //api接口路径
        String url = ApiCallUtil.getUrlFromProperties("api_url");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("prompt",string);
        System.out.println("JSON传参:"+jsonObject);
        String response = ApiCallUtil.doPost(url, jsonObject);

        return JSON.parseObject(response);
    }
}
